using io = System.IO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Runtime.Versioning;
using Dapper;
using groupModel = SocketTool.Model.DataModels.DbModel;
namespace SocketTool.Dll
{
    /// <summary>
    /// 协议分组信息
    /// </summary>
    public class ProtocolGroupDll
    {
        private static readonly string dbFolderPath =
            io.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SocketTool", "Db");

        private static readonly string dbPath = io.Path.Combine(dbFolderPath, "ProtocolGroup.db3");
        private static readonly string connectionString = $"Data Source={dbPath}";

        private SQLiteConnection mSQLiteCon
        {
            get { return new SQLiteConnection(connectionString); }
        }

        /// <summary>
        /// 检查数据库文件
        /// </summary>
        /// <param name="checkError"></param>
        public bool CheckDbFile(out string checkError)
        {
            try
            {
                checkError = string.Empty;
                if (!io.Directory.Exists(dbFolderPath))
                    io.Directory.CreateDirectory(dbFolderPath);

                var dbFileInfo = new io.FileInfo(dbPath);

                #region 检查表字段

                //if (dbFileInfo.Exists && dbFileInfo.Length > 0)
                //{
                //    return CheckDBColmns(out errorMsg);
                //}

                #endregion

                if (dbFileInfo.Exists)
                    return true;

                #region 创建数据库文件

                SQLiteConnection.CreateFile(dbPath);

                #endregion

                using (var sqlCon = mSQLiteCon)
                {
                    if (sqlCon.State != System.Data.ConnectionState.Open)
                        sqlCon.Open();

                    #region 创建ProtocolHeadInfo表

                    sqlCon.Execute(@"CREATE TABLE `ProtocolGroup` (
                                `GroupId`       INTEGER,
                                `GroupName`  TEXT,
                                PRIMARY KEY(`GroupId` AUTOINCREMENT)
                            ); ");

                    ///初始化分组信息时会初始化一个默认分组出来
                    sqlCon.Execute($"INSERT INTO ProtocolGroup (GroupName) VALUES('默认分组')");
                    #endregion
                }

                return true;
            }
            catch (Exception ex)
            {
                checkError = "连接记录表异常";
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"检查连接记录表异常：{ex.Message}");
                Console.ResetColor();
                return false;
            }
        }

        /// <summary>
        /// 添加新分组信息
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public int AddNewProtocolGroup(string groupName)
        {
            try
            {
                using (var sqlCon = this.mSQLiteCon)
                {
                    if (sqlCon.State != ConnectionState.Open)
                        sqlCon.Open();
                    var rowid = sqlCon.ExecuteScalar(
                        "INSERT INTO ProtocolGroup (GroupName) VALUES (@GroupName);select last_insert_rowid();", new {GroupName = groupName});
                    return int.Parse(rowid.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"添加新分组信息 AddNewProtocolGroup {ex.Message}");
                Console.ResetColor();
                return 0;
            }
        }

        /// <summary>
        /// 删除分组信息
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public bool DeleteProtocolGroup(int groupId)
        {
            try
            {
                using (var sqlCon = this.mSQLiteCon)
                {
                    if (sqlCon.State != ConnectionState.Open)
                        sqlCon.Open();
                    var rows = sqlCon.Execute("DELETE FROM ProtocolGroup WHERE GroupId=@Id", new {Id = groupId});
                    return rows > 0;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"删除分组信息 DeleteProtocolGroup {ex.Message}");
                Console.ResetColor();
                return false;
            }
        }

        /// <summary>
        /// 修改分组信息
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public bool UpdateProtocolGroup(groupModel.ProtocolGroup group)
        {
            try
            {
                using (var sqlCon = this.mSQLiteCon)
                {
                    if (sqlCon.State != ConnectionState.Open)
                        sqlCon.Open();
                    var rows = sqlCon.Execute("UPDATE ProtocolGroup SET GroupName=@GroupName WHERE GroupId=@GroupId", group);
                    return rows > 0;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"修改分组信息 UpdateProtocolGroup {ex.Message}");
                Console.ResetColor();
                return false;
            }
        }

        /// <summary>
        /// 获取所有分组信息
        /// </summary>
        /// <returns></returns>
        public List<groupModel.ProtocolGroup> GetProtocolGroupList()
        {
            try
            {
                using (var sqlCon = this.mSQLiteCon)
                {
                    if (sqlCon.State != ConnectionState.Open)
                        sqlCon.Open();
                    var list = sqlCon.Query<groupModel.ProtocolGroup>("SELECT GroupId,GroupName FROM ProtocolGroup").ToList();
                    return list;
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
                Console.ResetColor();
                return null;
            }
        }

        /// <summary>
        /// 搜索协议分组信息
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public List<groupModel.ProtocolGroup> SearchProtocolGroups(string search)
        {
            try
            {
                using (var sqlCon = this.mSQLiteCon)
                {
                    if(sqlCon.State != ConnectionState.Open)
                        sqlCon.Open();
                    string cmds = $"SELECT GroupId,GroupName FROM ProtocolGroup WHERE GroupName like '%{search}%'";
                    return sqlCon.Query<groupModel.ProtocolGroup>(cmds).ToList();
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Search ProtocolGroup Info Error   SearchProtocolGroups(\"{search}\")  {ex.Message}");
                Console.ResetColor();
                return null;
            }
        }
    }
}